﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Configuration;
using System.IO;
using System.Xml;
using System.Xml.XPath;

namespace Birthday
{
    class DataLayer
    {

        static string pathXml = ConfigurationSettings.AppSettings["pathXmlData"].ToString();
        static string pathTxt = ConfigurationSettings.AppSettings["pathTxtData"].ToString();

        public static string[] GetPeopleName()
        {
            //Open FileStream
            FileStream fs = new FileStream(pathXml, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            //Create the xmlDocument

            XmlDocument xmlDoc = new XmlDocument();
            //Load the xml data into XmlDocument
            xmlDoc.Load(fs);

            ArrayList name_SurName = new ArrayList();

            for (int i = 0; i < xmlDoc.DocumentElement.ChildNodes.Count; i++)
            {
                
                name_SurName.Add(xmlDoc.DocumentElement.ChildNodes[i].SelectSingleNode("name").InnerText +
                    " " + xmlDoc.DocumentElement.ChildNodes[i].SelectSingleNode("surName").InnerText);
            }

            fs.Close();
            return (string[])name_SurName.ToArray(typeof(string));
        }

        public static Man GetManDetails(string name,string surName)
        {
            Man man = new Man();
            XPathDocument xpDoc = new XPathDocument(pathXml);
            XPathNavigator nav = xpDoc.CreateNavigator();
            XPathNodeIterator iterator = nav.Select(string.Format(
                "PEOPLE/Man[name='{0}'and surName='{1}']",name,surName));

            if (iterator.Count != 1)
            {
                return man;
            }
            iterator.MoveNext();

            XPathNodeIterator innerIterator =
                iterator.Current.SelectChildren(XPathNodeType.Element);
            while (innerIterator.MoveNext())
            {
                man.ManInfo[innerIterator.Current.Name] = innerIterator.Current.Value;
            }           

            /*XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(pathXml);
            XmlNode root = xmlDoc.DocumentElement;

            XmlNode node = root.SelectSingleNode(string.Format("Man[name='{0}' and surName='{1}']", name, surName));

            XmlNodeList list = node.ChildNodes;

            for (int i = 0; i < list.Count; i++)
            {
                man.ManInfo[list.Item(i).Name] = list.Item(i).InnerText;
            }*/

            return man;
        }

        public static bool AddPerson(Man newMan,ref string message)
        {
            if (CheckForExistPerson(newMan))
            {
                message = "Такая персона уже имеется в БД";
                return false;
            }

            FileStream fs;
            XmlDocument xmlDoc = new XmlDocument();
            try
            {
                using (fs = new FileStream(pathXml, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    xmlDoc.Load(fs);
                    fs.Close();
                }
            }
            catch
            {
                message = "Не удалось создать персону. Файл БД поврежден или отсутствует.";
                return false;
            }

            try
            {
                XmlElement newItem;
                XmlElement newOuterItem = xmlDoc.CreateElement("Man");
                foreach (KeyValuePair<string, string> kvp in newMan.ManInfo)
                {
                    newItem = xmlDoc.CreateElement(kvp.Key);
                    newItem.InnerText = kvp.Value;
                    newOuterItem.AppendChild(newItem);
                }
                xmlDoc.DocumentElement.InsertAfter(newOuterItem, xmlDoc.DocumentElement.LastChild);
                FileStream writer = new FileStream(pathXml, FileMode.Truncate, FileAccess.Write, FileShare.ReadWrite);
                xmlDoc.Save(writer);
                writer.Dispose();               
            }
            catch
            {
                message = "Персону не удалось создать.";
                return false;
            }
            message = "Персона успешно создана.";
            return true;
        }
        public static bool DeletePerson(Man deletedMan)
        {
            XmlDocument xmlDoc = new XmlDocument();
            try
            {
                xmlDoc.Load(pathXml);

                XmlNode root = xmlDoc.DocumentElement;
                XmlNode node = root.SelectSingleNode(string.Format
                    ("Man[name='{0}' and surName='{1}' and mobilePhone='{2}']"
                    , deletedMan.Name, deletedMan.SurName, deletedMan.MobilePhone));
                XmlNode outer = node.ParentNode;
                outer.RemoveChild(node);
                xmlDoc.Save(pathXml);
            }
            catch
            {
                return false;
            }
            return true;
        }
        public static bool UpdatePerson(string currentName, string currentSurName, Man proposedMan)
        {
            XmlDocument xmlDoc = new XmlDocument();
            try
            {
                xmlDoc.Load(pathXml);
                XmlNode root = xmlDoc.DocumentElement;
                XmlNode node = root.SelectSingleNode(string.Format(
                    "Man[name='{0}'and surName ='{1}'",currentName,currentSurName));
                XmlNodeList list = node.ChildNodes;
                for (int i = 0; i < list.Count; i++)
                {
                    list.Item(i).InnerText = proposedMan.ManInfo[list.Item(i).Name];
                }
                FileStream fs = new FileStream(pathXml, FileMode.Truncate, FileAccess.Write, FileShare.ReadWrite);
                xmlDoc.Save(fs);//гудок это не писал!
                fs.Dispose();

            }
            catch
            {
                return false;
            }
            return true;
        }

        private static bool CheckForExistPerson(Man newMan)
        {
            XmlDocument xmlDoc;
            try
            {
                xmlDoc= new XmlDocument();
                xmlDoc.Load(pathXml);
            }
            catch
            {
                return true;
            }
            XmlNodeList xmlListName =xmlDoc.DocumentElement.GetElementsByTagName("name");
            XmlNodeList xmlListSurName = xmlDoc.DocumentElement.GetElementsByTagName("surName");

            for (int j = 0; j < xmlListName.Count; j++)
            {
                if (xmlListName[j].InnerText == newMan.ManInfo["name"] &&
                    xmlListSurName[j].InnerText == newMan.ManInfo["surName"])
                    return true;
            }
            return false;
            
        }
    }
}
